package com.easyattendance.services;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.easyattendance.model.Class;
import com.easyattendance.model.Proxy;
import com.easyattendance.model.Student;
import com.easyattendance.model.Subject;
import com.easyattendance.model.SubjectClass;
import com.easyattendance.model.SubjectTeacher;
import com.easyattendance.model.TimeTable;
import com.easyattendance.util.HibernateUtil;

public class AddSubjectService {

	/* Method to CREATE a subject in the database */
	   public synchronized boolean addSubject(Subject subject){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();

	         	
	        	 session.save(subject);
	           	 tx.commit();
              
	           result=true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return result;
	   }
	   
	   /* Method to UPDATE a subject in the database */
	   public synchronized boolean updateSubject(Subject subject){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();
	        	 session.update(subject);
	           	 tx.commit();
              
	           result=true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return result;
	   }
	   
	   /* Method to DELETE an subject from the records */
	   public synchronized boolean deleteSubject(String subjectId){
		   Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean flag = false;
	      try{
	         tx = session.beginTransaction();
	         Subject subject= (Subject) session.createQuery("FROM Subject where subject_id='"+subjectId+"'").uniqueResult();
	         session.delete(subject);
	         
	         tx.commit();
	         flag = true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return flag;
	   }
	   
	   public int getSubjectIdValue()
	   {
		   	Session session = HibernateUtil.openSession();
	        Transaction tx = null;
	        int value=0;
	        try {
	            tx = session.getTransaction();
	            tx.begin();
	            SQLQuery query = session.createSQLQuery("select MAX(subject_id) from tbl_subject");
	           
	            if(query.uniqueResult()!=null)
	            {
	            	String subject_id=(String) query.uniqueResult();
	            	String subject_counter=subject_id.substring(3);
	            	value = Integer.parseInt(subject_counter)+1;
	            }
	            else
	            	value=1;
	            
	            tx.commit();
	        } catch (Exception e) {
	            if (tx != null) {
	                tx.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.close();
	        }
		   
		   return value;
	   }
	   
	   /* Method to CREATE mapping of subject and teacher in the database */
	   public synchronized boolean addTeacherSubject(SubjectTeacher subteacher){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();

	         	
	        	 session.save(subteacher);
	           	 tx.commit();
              
	           result=true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return result;
	   }
	   
	   /* Method to CREATE mapping of subject and class in the database */
	   public synchronized boolean addSubjectClass(SubjectClass subClass){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();

	         	
	        	 session.save(subClass);
	           	 tx.commit();
              
	           result=true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return result;
	   }
	   
	   /* Method to UPDATE mapping of subject and class in the database */
	   public synchronized boolean updateSubjectClass(SubjectClass subClass){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();

	         	
	        	 session.update(subClass);
	           	 tx.commit();
              
	           result=true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return result;
	   }
	   
	   /* Method to UPDATE mapping of subject and teacher in the database */
	   public synchronized boolean updateTeacherSubject(SubjectTeacher subteacher){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();

	         	
	        	 session.update(subteacher);
	           	 tx.commit();
              
	           result=true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return result;
	   }
	   
	   public boolean ifAlreadyExists(String subjectName) {
			 boolean flag = getUserByUserId(subjectName);
			 
			 return flag;

		}
	   
	   public boolean ifAlreadyExists(Subject newSubject) {
			 boolean flag = false;
			 
			 Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List subjects = null;
		      try{
		         tx = session.beginTransaction();
		         subjects = session.createQuery("FROM Subject").list(); 
		         for (Iterator iterator = subjects.iterator(); iterator.hasNext();){
		        	 Subject subject = (Subject) iterator.next(); 
		            if(subject.getSubject_name().equals(newSubject.getSubject_name())) {
		            	System.out.println("Subject already exists");
		            	flag = true;
		            	break;
		            }
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
			 
			 return flag;
		}
	   
	   public boolean ifSubTeacherAlreadyExists(String subjectId, String teacherId) {
			 boolean flag = false;
			 
			 Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      try{
		         tx = session.beginTransaction();
		         Query query = session.createQuery("FROM SubjectTeacher where subject_id='"+subjectId+"' and teacher_id='"+teacherId+"'");
		         
		         if(query != null) {
		        	 SubjectTeacher newSubTeacher = (SubjectTeacher) query.uniqueResult();
			         if(newSubTeacher!=null) {
			        	 flag = true;   
			         }
			         else {
			        	 flag = false;
			         }
		         }
		         
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
			 
			 return flag;
		}
	   
	   /*  get subject_teacher record*/
	   public SubjectTeacher getSubTeacherByIds(String subjectId, String teacherId) {
			 boolean flag = false;
			 
			 Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      SubjectTeacher newSubTeacher = null;
		      try{
		         tx = session.beginTransaction();
		         Query query = session.createQuery("FROM SubjectTeacher where subject_id='"+subjectId+"' and teacher_id='"+teacherId+"'");
		         
		         if(query != null) {
		        	 newSubTeacher = (SubjectTeacher) query.uniqueResult();
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return newSubTeacher;
		}
	   
	   public synchronized void deleteSubTeachers(String subjectId) {
			 Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List<SubjectTeacher> subTeachers=null;
		      try{
		         tx = session.beginTransaction();
		         Query query = session.createQuery("DELETE FROM SubjectTeacher where subject_id='"+subjectId+"'");
		         int rowCount = query.executeUpdate();
		         
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		}
	   
	   
		public boolean getUserByUserId(String subjectName) {
			 Session session = HibernateUtil.openSession();
			 Transaction tx = null;
			 Subject subject = null;
			 Query query=null;
			 boolean flag = false;
			 try {
				 tx = session.getTransaction();
				 tx.begin();
				// tx = session.beginTransaction();
				 query = session.createQuery("from Subject where subject_name='"+subjectName+"'");
				 List list = query.list();
				 			 
				 if (list.isEmpty()) {
					 flag = false;
				 }
				 else {
					 flag = true;
				 }
				 if (!tx.wasCommitted()) {
					 tx.commit();
				 }
					 
			 } catch (Exception e) {
				 if (tx != null) {
					 tx.rollback();
				 }
				 e.printStackTrace();
			 } finally {
				 session.close();
			 }
			return flag;
		}
	   
		/* Method to  READ all the subjects values */
		   public List listSubjects( ) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List subjects = null;
		      try{
		         tx = session.beginTransaction();
		         subjects = session.createQuery("FROM Subject").list(); 
		         for (Iterator iterator = subjects.iterator(); iterator.hasNext();){
		        	Subject subject = (Subject) iterator.next(); 
		            System.out.print("SubjectName: " + subject.getSubject_name()); 
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return subjects;
		   }
		   
		   /* Method to  subject by subject id */
		   public Subject getSubjectBySubjectId(String subjectId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      Subject subject = new Subject();
		      try{
		         tx = session.beginTransaction();
		         /*Query query = session.createSQLQuery("select s.* FROM tbl_subject s, tbl_department d where s.section_id = d.section_id "
			         		+ "and d.section_email_id='"+sectionEmailID+"'");
		         subjects = query.list();*/
		         //subjects = session.createQuery("FROM Subject s inner join fetch s.department as d where s.section_id = d.section_id "+ "and d.section_email_id='"+sectionEmailID+"'").list(); 
		         Query query  = session.createQuery("FROM Subject where subject_id='"+subjectId+"'");
		         
		         subject = (Subject) query.uniqueResult();
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return subject;
		   }
		   
		   /* Method to  subject id by subject name */
		   public String getSubjectIdBySubjectName(String subjectName) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      Subject subject = new Subject();
		      try{
		         tx = session.beginTransaction();
		         /*Query query = session.createSQLQuery("select s.* FROM tbl_subject s, tbl_department d where s.section_id = d.section_id "
			         		+ "and d.section_email_id='"+sectionEmailID+"'");
		         subjects = query.list();*/
		         //subjects = session.createQuery("FROM Subject s inner join fetch s.department as d where s.section_id = d.section_id "+ "and d.section_email_id='"+sectionEmailID+"'").list(); 
		         Query query  = session.createQuery("FROM Subject where subject_name='"+subjectName+"'");
		         
		         subject = (Subject) query.uniqueResult();
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return subject.getSubject_id();
		   }
		   
		   /* Method to  subject id by subject name for particular class*/
		   public String getSubjectIdBySubjectNameForClass(String subjectName,String classId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      Subject subject = new Subject();
		      try{
		         tx = session.beginTransaction();
		         /*Query query = session.createSQLQuery("select s.* FROM tbl_subject s, tbl_department d where s.section_id = d.section_id "
			         		+ "and d.section_email_id='"+sectionEmailID+"'");
		         subjects = query.list();*/
		         //subjects = session.createQuery("FROM Subject s inner join fetch s.department as d where s.section_id = d.section_id "+ "and d.section_email_id='"+sectionEmailID+"'").list(); 
		         Query query  = session.createQuery("FROM Subject where subject_name='"+subjectName+"' and class_id='"+classId+"'");
		         
		         subject = (Subject) query.uniqueResult();
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return subject.getSubject_id();
		   }


		   /* Method to  READ all the subjects of particular section */
		   public List listSubjects(String sectionId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List subjects = null;
		      try{
		         tx = session.beginTransaction();
		         /*Query query = session.createSQLQuery("select s.* FROM tbl_subject s, tbl_department d where s.section_id = d.section_id "
			         		+ "and d.section_email_id='"+sectionEmailID+"'");
		         subjects = query.list();*/
		         //subjects = session.createQuery("FROM Subject s inner join fetch s.department as d where s.section_id = d.section_id "+ "and d.section_email_id='"+sectionEmailID+"'").list(); 
		         subjects = session.createQuery("FROM Subject where section_id='"+sectionId+"'").list();
		         for (Iterator iterator = subjects.iterator(); iterator.hasNext();){
		        	Subject subject = (Subject) iterator.next(); 
		            System.out.print("SubjectName: " + subject.getSubject_name()); 
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return subjects;
		   }
		   
		   /* Method to  READ all the subjects of particular class */
		   public List listSubjectsByClassId(String classId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List subjects = null;
		      try{
		         tx = session.beginTransaction(); 
		         subjects = session.createQuery("FROM Subject where class_id='"+classId+"'").list();
		         for (Iterator iterator = subjects.iterator(); iterator.hasNext();){
		        	Subject subject = (Subject) iterator.next(); 
		            System.out.print("SubjectName: " + subject.getSubject_name()); 
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return subjects;
		   }
		   
		   /* Method to  READ all the elective types of particular class */
		   public List listElectiveTypesByClassId(String classId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List subjects = null;
		      List electiveTypes = new ArrayList();
		      try{
		         tx = session.beginTransaction(); 
		         subjects = session.createQuery("FROM Subject where class_id='"+classId+"'").list();
		         for (Iterator iterator = subjects.iterator(); iterator.hasNext();) {
		        	 Subject subject = (Subject) iterator.next();
		        	 if( !electiveTypes.contains(subject.getCategory())) {
		        		 electiveTypes.add(subject.getCategory());
		        	 }
		            //System.out.print("SubjectName: " + subject.getSubject_name()); 
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return electiveTypes;
		   }
		   
		   /* Method to  READ all the subjects that are not occupied on a day for a timeslot */
		   public List<Subject> listSubjectsOnDayForTimeSlot(String day, String timeSlot, String teacherEmail) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List<Subject> subjects = new ArrayList<Subject>();
		      
		      List<TimeTable> timeTable = null;
		      AddTeacherService teacherService = new AddTeacherService();
		      AddClassService classService = new AddClassService();
		      try{
		         tx = session.beginTransaction();
		         String sectionId = teacherService.getSectionIdByTeacherId(teacherEmail);
		         String classId = classService.getClassIdByTeacherId(teacherEmail);
		         
		         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		         /*Date tempSlot=null;
				 try {
					tempSlot = format.parse("2013-10-10 "+timeSlot+":00");
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}*/
		         String tempSlot="2013-10-10 "+timeSlot+":00";
		        
				 /*List<TimeTable> test = session.createQuery("FROM TimeTable").list();
				 for (Iterator<TimeTable> iterator = test.iterator(); iterator.hasNext();){
			        	TimeTable tempTT = (TimeTable) iterator.next(); 
			            System.out.println("SubjectName: " + tempTT.getSubject_id());
			            System.out.println("TIMESLOT: " + tempTT.getTime_slot());
				 }*/
		         timeTable = session.createQuery("FROM TimeTable where day_of_week ='"+day+"' and time_slot='"+tempSlot+"' and section_id='"+sectionId+"'").list();
		         
		         if(timeTable.isEmpty()) {
		        	 subjects = session.createQuery("FROM Subject where section_id='"+sectionId+"' and class_id='"+classId+"'").list();
		         }
		         else {
		        	 for (Iterator<TimeTable> iterator = timeTable.iterator(); iterator.hasNext();){
				        	TimeTable tempTT = (TimeTable) iterator.next(); 
				            System.out.println("SubjectName: " + tempTT.getSubject().getSubject_id());
				            System.out.println("TIMESLOT: " + tempTT.getTime_slot());
				             
				         
				           List query = session.createQuery("FROM Subject where subject_id !='"+tempTT.getSubject().getSubject_id()+"' "
				            		+ "and section_id='"+sectionId+"' and class_id='"+classId+"'").list();
				           for (Iterator subjectIterator = query.iterator(); subjectIterator.hasNext();) {
				        	   	Subject tempSubject = (Subject) subjectIterator.next();
					            subjects.add(tempSubject);
					            System.out.println("SIZE IN java: "+subjects.size());
				           }
				            
				            /*for (Iterator<Subject> ttIterator = tempSubject.iterator(); iterator.hasNext();){
				            	subjects.add((Subject) ttIterator.next());	             
				            }*/
			         }
		         }
		         
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return subjects;
		   }
		   
		   /* Method to READ all the subjects the passed elective type(category) of particular class */
		   public List listSubjectsByElectiveType(String elective, String classId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List subjects = null;
		      try{
		         tx = session.beginTransaction(); 
		         subjects = session.createQuery("FROM Subject where category='"+elective+"' and class_id='"+classId+"'").list();
		         
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return subjects;
		   }
		   
		   /* Method to READ all the subjects taught by a teacher */
		   public List listSubjectsByTeacherId(String teacherId, String classId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List tempSubjects = new ArrayList();
		      List subjects = new ArrayList();
		      
		      AddTeacherService teacherService = new AddTeacherService();
		      AddSubjectService addSubjectService = new AddSubjectService();
		      String deptId = teacherService.getTeacherById(teacherId).getSection().getSection_id();
		      try{
		         tx = session.beginTransaction(); 
		         tempSubjects = session.createQuery("FROM SubjectTeacher where teacher_id='"+teacherId+"'").list();
		         
		         Iterator iterator = tempSubjects.iterator();
		         
		         while(iterator.hasNext()) {
		        	 SubjectTeacher subjTeacher = (SubjectTeacher) iterator.next();
		        	 
		        	 Query query = session.createQuery("FROM Subject where subject_id='"+subjTeacher.getSubject_id()+"'");
		        	 subjects.add((Subject) query.uniqueResult());
		        	 
		        }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return subjects;
		   }
		   
		   public List listSubjectsByTeacherIdForClass(String teacherId,String classId)
		   {
			      Session session = HibernateUtil.openSession();
			      Transaction tx = null;
			      List subjects = new ArrayList();
			      List<SubjectTeacher> sub_teacherList=new ArrayList<SubjectTeacher>();
			      //List<SubjectClass> sub_classes = new ArrayList<SubjectClass>();
			      
			      try
			      {
			    	     tx = session.beginTransaction(); 
				         sub_teacherList = session.createQuery("FROM SubjectTeacher where teacher_id='"+teacherId+"'").list();
			      
				         for(Iterator subItr=sub_teacherList.iterator();subItr.hasNext();)
				         {
				        	    SubjectTeacher sub_teacher=(SubjectTeacher) subItr.next();
				        	    SQLQuery query=session.createSQLQuery("select sub_class.subject_id from tbl_subject_class sub_class,tbl_subject sub where sub.subject_id=sub_class.subject_id"
				        	    		+" and sub_class.subject_id='"+sub_teacher.getSubject_id()+"' and sub_class.class_id='"+classId+"'");
				        	    
				        	    if(query.uniqueResult()!=null)
				        	    	  subjects.add((String)query.uniqueResult());
				         }
				        	 
				     tx.commit();    
			      }
		   		  catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
			      
			     return subjects; 
		   }
		   
		   /* Method to get SubjectClass object for a particular subject of particular class */
		   public SubjectClass getSubjectClassByIds(String subjectId, String classId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      SubjectClass subjectClass = null;
		      try{
		         tx = session.beginTransaction();
		         /*Query query = session.createSQLQuery("select s.* FROM tbl_subject s, tbl_department d where s.section_id = d.section_id "
			         		+ "and d.section_email_id='"+sectionEmailID+"'");
		         subjects = query.list();*/
		         //subjects = session.createQuery("FROM Subject s inner join fetch s.department as d where s.section_id = d.section_id "+ "and d.section_email_id='"+sectionEmailID+"'").list(); 
		         Query query  = session.createQuery("FROM SubjectClass where subject_id='"+subjectId+"' and class_id='"+classId+"'");
		         
		         subjectClass = (SubjectClass) query.uniqueResult();
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return subjectClass;
		   }
		   
		   
		   /* Method to get lecture stauts of a subject_teacher record */
		   public int getSubjectTeacherStatusByIds(String teacherId, String subjectId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      SubjectTeacher subjectTeacher = null;
		      
		      AddTeacherService teacherService = new AddTeacherService();
		      String deptId = teacherService.getTeacherById(teacherId).getSection().getSection_id();
		      try{
		         tx = session.beginTransaction(); 
		         Query query = session.createQuery("FROM SubjectTeacher where teacher_id='"+teacherId+"' and subject_id='"+subjectId+"'");
		         
		         if(query.uniqueResult() != null) {
	        		 subjectTeacher = (SubjectTeacher)query.uniqueResult();
	        	 }
		         
		       tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      
		      if(subjectTeacher!=null)
		    	  return subjectTeacher.getLecture_status();
		      else {
		    	  return 1000;
		      }
		   }
		   
		   /* Method to get lecture stauts of a subject_class record */
		   public int getSubjectStatusById(String subjectId, String classId) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      SubjectClass subjectClass = null;
		      
		     
		      try{
		         tx = session.beginTransaction(); 
		         Query query = session.createQuery("FROM SubjectClass where subject_id='"+subjectId+"' and class_id='"+classId+"'");
		         
		         if(query.uniqueResult() != null) {
		        	 subjectClass = (SubjectClass)query.uniqueResult();
	        	 }
		         
		       tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      
		      if(subjectClass!=null)
		    	  return subjectClass.getLecture_hours_counter();
		      else {
		    	  return 1000;
		      }
		   }
	   

		   /* Method to increment subject_class counter for all subjects in that class for sysdate*/
		   
		   public void incrementLectureStatus(String sectionEmailId, String classId) {
			   Date sysDate = new Date();
			   
			   AddProxyService proxyService = new AddProxyService();
			   AddAllTimeSlotsService timeTableService = new AddAllTimeSlotsService();
			   String[] timeSlots = timeTableService.listAllTimeSlotsBySection(sectionEmailId);
			   String tmpTime = null;
			   String[] teacherIds = new String[9];
			   String[] subjectIds = new String[9];
			   TimeTable timeTable = null;
			   Proxy proxy = null;
			   SubjectClass subjectClass = null;
			   
			   int today = sysDate.getDay();
			   String day = null;
			   
			   switch(today){
			   	case 0:
				   day = "Sunday";
				   break;
			   	case 1:
				   day = "Monday";
				   break;
			   	case 2:
				   day = "Tuesday";
				   break;
			   	case 3:
				   day = "Wednesday";
				   break;
			   	case 4:
				   day = "Thursday";
				   break;
			   	case 5:
				   day = "Friday";
				   break;
			   	case 6:
				   day = "Saturday";
				   break;
				 
			   }
			   Session session = HibernateUtil.openSession();
				Transaction tx = null;
				
				try {
					tx = session.beginTransaction();
					
					for(int i=0, j=0; i<timeSlots.length; i++) {
						tmpTime = "2013-10-10 "+timeSlots[i]+":00";
						
						Query query = session.createQuery("FROM TimeTable WHERE day_of_week='" + day + "' and time_slot='"+tmpTime+"' "
								+ "and class_id='"+classId+"'");
						
						
						if(query.uniqueResult()!=null) {
							timeTable = (TimeTable) query.uniqueResult();
							//check if this subject has a proxy or not and accordingly increment lecture hours
							proxy = proxyService.getProxyOnDayForTimeSlot(day, tmpTime, classId, timeTable.getSubject_id());
							
							if(proxy!=null) {
								subjectIds[j] = proxy.getProxy_subject_id();
							}
							else {
								subjectIds[j] = timeTable.getSubject_id();
							}
						}
					}
					
					for(int j=0; j<subjectIds.length; j++) {
						Query query = session.createQuery("FROM SubjectClass where subject_id='"+subjectIds[j]+"'");
						if(query.uniqueResult()!=null) {
							subjectClass = (SubjectClass) query.uniqueResult();
							
							subjectClass.setLecture_hours_counter( (subjectClass.getLecture_hours_counter()) +1);
							session.update(subjectClass);
						}
					}
					tx.commit();
					} catch (HibernateException e) {
						if (tx != null)
							tx.rollback();
						e.printStackTrace();
					} finally {
						session.close();
					}
			   
		   	}
	   
}
